package com.ynr.sales.service.impl;

import java.io.File;
import java.io.IOException;
import java.util.Random;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.ynr.sales.service.ISalesService;
import com.ynr.voucher.service.IVoucherSalesService;

@Service
public class SalesServiceImpl implements ISalesService {
	
	private static final Logger logger = LoggerFactory.getLogger(SalesServiceImpl.class);

	@Autowired
	private IVoucherSalesService voucherSalesService;
	
	@Override
	public void uploadSales(String billDate, int companyId, String rootPath, MultipartFile multifile) {
		String filePath = rootPath + "/" + getGernarateFileName(multifile);
		try {
			FileUtils.copyInputStreamToFile(multifile.getInputStream(),
					new File(filePath));
		} catch (IOException e) {
			logger.error("SalesServiceImpl uploadSales method create file error : {}", e.toString());
		}
		voucherSalesService.processSalesExcel(filePath, companyId, billDate);
		
	}

	private String getGernarateFileName(MultipartFile file) {
		Random rdm = new Random(System.currentTimeMillis());
		String extendName = file.getOriginalFilename().substring(
				file.getOriginalFilename().lastIndexOf(".") + 1);
		return System.currentTimeMillis() + Math.abs(rdm.nextInt())
				% 1000 + (extendName == null ? ".unknown" : "." + extendName);
	}
	
}
